package com.ming.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAcpect {
    // 定义切入点
    @Pointcut("execution(public * com.ming..*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        // 接收请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录请求的内容
        log.info("URL:{}",request.getRequestURL().toString());
        log.info("HTTP_METHOD:{}",request.getMethod());
        log.info("IP:{}",request.getRemoteAddr());
        log.info("CLASS_METHOD:{}.{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());// 类和方法
        log.info("ARGS:{}", Arrays.toString(joinPoint.getArgs()));// 参数
    }

    /**
     *
     * @param R 表示返回值
     */
    @AfterReturning(returning = "R",pointcut = "log()")
    public void doAfterReturning(Object R){
        log.info("RESPONSE:{}",R);
    }


}
